#!/bin/bash
# LingShu消息队列 - Docker容器启动脚本

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

log_debug() {
    if [[ "${LINGSHU_DEBUG:-false}" == "true" ]]; then
        echo -e "${BLUE}[DEBUG]${NC} $1"
    fi
}

# 显示启动横幅
show_banner() {
    cat << 'EOF'
    
    ██╗     ██╗███╗   ██╗ ██████╗ ███████╗██╗  ██╗██╗   ██╗
    ██║     ██║████╗  ██║██╔════╝ ██╔════╝██║  ██║██║   ██║
    ██║     ██║██╔██╗ ██║██║  ███╗███████╗███████║██║   ██║
    ██║     ██║██║╚██╗██║██║   ██║╚════██║██╔══██║██║   ██║
    ███████╗██║██║ ╚████║╚██████╔╝███████║██║  ██║╚██████╔╝
    ╚══════╝╚═╝╚═╝  ╚═══╝ ╚═════╝ ╚══════╝╚═╝  ╚═╝ ╚═════╝ 
    
    高性能消息队列系统 v1.0.0
    
EOF
}

# 检查环境变量
check_environment() {
    log_info "检查环境配置..."
    
    # 设置默认值
    export LINGSHU_HOST="${LINGSHU_HOST:-0.0.0.0}"
    export LINGSHU_PORT="${LINGSHU_PORT:-4222}"
    export LINGSHU_HTTP_PORT="${LINGSHU_HTTP_PORT:-8222}"
    export LINGSHU_CLUSTER_PORT="${LINGSHU_CLUSTER_PORT:-6222}"
    export LINGSHU_MONITOR_PORT="${LINGSHU_MONITOR_PORT:-5222}"
    export LINGSHU_LOG_LEVEL="${LINGSHU_LOG_LEVEL:-info}"
    export LINGSHU_MAX_CONNECTIONS="${LINGSHU_MAX_CONNECTIONS:-1000}"
    export LINGSHU_MAX_PAYLOAD="${LINGSHU_MAX_PAYLOAD:-1048576}"
    
    log_debug "LINGSHU_HOST: $LINGSHU_HOST"
    log_debug "LINGSHU_PORT: $LINGSHU_PORT"
    log_debug "LINGSHU_HTTP_PORT: $LINGSHU_HTTP_PORT"
    log_debug "LINGSHU_CLUSTER_PORT: $LINGSHU_CLUSTER_PORT"
    log_debug "LINGSHU_MONITOR_PORT: $LINGSHU_MONITOR_PORT"
    log_debug "LINGSHU_LOG_LEVEL: $LINGSHU_LOG_LEVEL"
}

# 初始化数据目录
init_data_directory() {
    log_info "初始化数据目录..."
    
    # 创建必要的子目录
    mkdir -p "$LINGSHU_DATA_DIR/jetstream"
    mkdir -p "$LINGSHU_DATA_DIR/storage"
    mkdir -p "$LINGSHU_DATA_DIR/cluster"
    mkdir -p "$LINGSHU_LOG_DIR"
    
    # 设置权限
    chmod 755 "$LINGSHU_DATA_DIR"
    chmod 755 "$LINGSHU_LOG_DIR"
    
    log_info "数据目录初始化完成"
}

# 生成配置文件
generate_config() {
    log_info "生成LingShu配置文件..."
    
    local config_file="$LINGSHU_CONFIG_DIR/lingshu.conf"
    
    cat > "$config_file" << EOF
# LingShu消息队列配置文件
# 由Docker容器自动生成

# 服务器配置
server {
    host = "$LINGSHU_HOST"
    port = $LINGSHU_PORT
    max_connections = $LINGSHU_MAX_CONNECTIONS
    max_payload = $LINGSHU_MAX_PAYLOAD
}

# HTTP监控配置
http {
    host = "$LINGSHU_HOST"
    port = $LINGSHU_HTTP_PORT
}

# 集群配置
cluster {
    host = "$LINGSHU_HOST"
    port = $LINGSHU_CLUSTER_PORT
    name = "${LINGSHU_CLUSTER_NAME:-lingshu-cluster}"
}

# 日志配置
logging {
    level = "$LINGSHU_LOG_LEVEL"
    file = "$LINGSHU_LOG_DIR/lingshu.log"
    max_size = "${LINGSHU_LOG_MAX_SIZE:-100MB}"
    max_files = ${LINGSHU_LOG_MAX_FILES:-10}
}

# 存储配置
storage {
    type = "${LINGSHU_STORAGE_TYPE:-memory}"
    data_dir = "$LINGSHU_DATA_DIR/storage"
}

# JetStream配置
jetstream {
    enabled = ${LINGSHU_JETSTREAM_ENABLED:-true}
    store_dir = "$LINGSHU_DATA_DIR/jetstream"
    max_memory = "${LINGSHU_JETSTREAM_MAX_MEMORY:-1GB}"
    max_file = "${LINGSHU_JETSTREAM_MAX_FILE:-10GB}"
}

# 性能优化配置
performance {
    write_deadline = "${LINGSHU_WRITE_DEADLINE:-2s}"
    max_pending = ${LINGSHU_MAX_PENDING:-67108864}
}
EOF

    log_info "配置文件生成完成: $config_file"
}

# 检查端口可用性
check_ports() {
    log_info "检查端口可用性..."
    
    local ports=("$LINGSHU_PORT" "$LINGSHU_HTTP_PORT" "$LINGSHU_CLUSTER_PORT" "$LINGSHU_MONITOR_PORT")
    
    for port in "${ports[@]}"; do
        if netstat -ln 2>/dev/null | grep -q ":$port "; then
            log_warn "端口 $port 已被占用"
        else
            log_debug "端口 $port 可用"
        fi
    done
}

# 等待依赖服务
wait_for_dependencies() {
    if [[ -n "${LINGSHU_WAIT_FOR}" ]]; then
        log_info "等待依赖服务: $LINGSHU_WAIT_FOR"
        
        IFS=',' read -ra DEPS <<< "$LINGSHU_WAIT_FOR"
        for dep in "${DEPS[@]}"; do
            IFS=':' read -ra HOST_PORT <<< "$dep"
            local host="${HOST_PORT[0]}"
            local port="${HOST_PORT[1]:-4222}"
            
            log_info "等待 $host:$port 可用..."
            while ! nc -z "$host" "$port" 2>/dev/null; do
                sleep 1
            done
            log_info "$host:$port 已可用"
        done
    fi
}

# 设置信号处理
setup_signal_handlers() {
    log_info "设置信号处理器..."
    
    # 优雅关闭处理
    trap 'log_info "收到SIGTERM信号，开始优雅关闭..."; kill -TERM $PID; wait $PID' TERM
    trap 'log_info "收到SIGINT信号，开始优雅关闭..."; kill -INT $PID; wait $PID' INT
}

# 启动LingShu服务器
start_lingshu() {
    log_info "启动LingShu消息队列服务器..."
    
    local config_file="$LINGSHU_CONFIG_DIR/lingshu.conf"
    local cmd="$LINGSHU_HOME/bin/lingshu-server"
    
    # 添加配置文件参数
    if [[ -f "$config_file" ]]; then
        cmd="$cmd --config $config_file"
    fi
    
    # 添加其他参数
    if [[ "${LINGSHU_DEBUG:-false}" == "true" ]]; then
        cmd="$cmd --debug"
    fi
    
    if [[ -n "${LINGSHU_CLUSTER_ROUTES}" ]]; then
        cmd="$cmd --routes $LINGSHU_CLUSTER_ROUTES"
    fi
    
    log_info "执行命令: $cmd"
    
    # 启动服务器
    exec $cmd &
    PID=$!
    
    log_info "LingShu服务器已启动 (PID: $PID)"
    
    # 等待进程结束
    wait $PID
}

# 主函数
main() {
    show_banner
    
    log_info "LingShu Docker容器启动中..."
    log_info "容器版本: ${LINGSHU_VERSION:-1.0.0}"
    log_info "构建时间: ${BUILD_DATE:-未知}"
    log_info "Git提交: ${GIT_COMMIT:-未知}"
    
    # 执行初始化步骤
    check_environment
    init_data_directory
    generate_config
    check_ports
    wait_for_dependencies
    setup_signal_handlers
    
    # 如果传入了参数，执行对应的命令
    if [[ $# -gt 0 ]]; then
        case "$1" in
            "lingshu-server")
                start_lingshu
                ;;
            "bash"|"sh")
                log_info "启动交互式shell..."
                exec "$@"
                ;;
            "version")
                echo "LingShu v${LINGSHU_VERSION:-1.0.0}"
                exit 0
                ;;
            "help")
                echo "LingShu Docker容器使用说明:"
                echo "  lingshu-server  - 启动LingShu服务器（默认）"
                echo "  bash/sh         - 启动交互式shell"
                echo "  version         - 显示版本信息"
                echo "  help            - 显示此帮助信息"
                exit 0
                ;;
            *)
                log_info "执行自定义命令: $*"
                exec "$@"
                ;;
        esac
    else
        # 默认启动服务器
        start_lingshu
    fi
}

# 执行主函数
main "$@"
